//
//  TWBaseViewModel.m
//  TWHomework-WeChat
//
//  Created by wzb on 2019/11/12.
//  Copyright © 2019 WZB. All rights reserved.
//

#import "TWBaseViewModel.h"

@interface TWBaseViewModel ()

// 存放所有请求
@property(strong, nonatomic) NSPointerArray *requestArrary;

@end

@implementation TWBaseViewModel

- (instancetype)init {
    self = [super init];
    if (self) {
        self.requestArrary = [NSPointerArray weakObjectsPointerArray];
    }

    return self;
}

- (void)registerRequest:(NSURLSessionDataTask *)operation {
    if (operation != nil) {
        [_requestArrary addPointer:(__bridge void *) operation];
    }
}

- (void)cancelAllHTTPRequest {
    NSArray *reqArray = self.requestArrary.allObjects;
    if (reqArray != nil && [reqArray count] > 0) {
        for (NSInteger i = (NSInteger) ([reqArray count] - 1); i >= 0; --i) {
            NSURLSessionDataTask *operation = reqArray[i];
            [[TWWebClient sharedClient] removeOperation:operation];
        }
    }
}

- (void)dealloc {
    [self cancelAllHTTPRequest];
    NSLog(@"dealloc %@ %ld", NSStringFromClass([self class]), (unsigned long) self.requestArrary.count);
}
@end
